{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 载入数据\n",
    "data = np.genfromtxt(\"data.csv\", delimiter=\",\")\n",
    "x_data = data[:,0]\n",
    "y_data = data[:,1]\n",
    "plt.scatter(x_data,y_data)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 学习率learning rate\n",
    "lr = 0.0001\n",
    "# 截距\n",
    "b = 0 \n",
    "# 斜率\n",
    "k = 0 \n",
    "# 最大迭代次数\n",
    "epochs = 50\n",
    "\n",
    "# 最小二乘法\n",
    "def compute_error(b, k, x_data, y_data):\n",
    "    totalError = 0\n",
    "    for i in range(0, len(x_data)):\n",
    "        totalError += (y_data[i] - (k * x_data[i] + b)) ** 2\n",
    "    return totalError / float(len(x_data))\n",
    "\n",
    "def gradient_descent_runner(x_data, y_data, b, k, lr, epochs):\n",
    "    # 计算总数据量\n",
    "    m = float(len(x_data))\n",
    "    # 循环epochs次\n",
    "    for i in range(epochs):\n",
    "        b_grad = 0\n",
    "        k_grad = 0\n",
    "        # 计算梯度的总和再求平均\n",
    "        for j in range(0, len(x_data)):\n",
    "            b_grad += -(1/m) * (y_data[j] - ((k * x_data[j]) + b))\n",
    "            k_grad += -(1/m) * x_data[j] * (y_data[j] - ((k * x_data[j]) + b))\n",
    "        # 更新b和k\n",
    "        b = b - (lr * b_grad)\n",
    "        k = k - (lr * k_grad)\n",
    "        # 每迭代5次，输出一次图像\n",
    "#         if i % 5==0:\n",
    "#             print(\"epochs:\",i)\n",
    "#             plt.plot(x_data, y_data, 'b.')\n",
    "#             plt.plot(x_data, k*x_data + b, 'r')\n",
    "#             plt.show()\n",
    "    return b, k"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(\"Starting b = {0}, k = {1}, error = {2}\".format(b, k, compute_error(b, k, x_data, y_data)))\n",
    "print(\"Running...\")\n",
    "b, k = gradient_descent_runner(x_data, y_data, b, k, lr, epochs)\n",
    "print(\"After {0} iterations b = {1}, k = {2}, error = {3}\".format(epochs, b, k, compute_error(b, k, x_data, y_data)))\n",
    "\n",
    "# 画图\n",
    "plt.plot(x_data, y_data, 'b.')\n",
    "plt.plot(x_data, k*x_data + b, 'r')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
